package com.hui.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hui.server.entity.MenuRole;
import com.hui.server.mapper.MenuRoleMapper;
import com.hui.server.service.MenuRoleService;
import com.hui.server.util.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.sql.SQLException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hui
 * @since 2022-03-31
 */
@Service
@Slf4j
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements MenuRoleService {

    private MenuRoleMapper mapper;

    @Autowired
    public MenuRoleServiceImpl(MenuRoleMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 更新角色拥有的菜单，先删除再插入
     *<p>@Transactional(isolation = Isolation.SERIALIZABLE)：设置事务隔离级别<p/>
     * @param rid
     * @param mids
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE,rollbackFor = Exception.class)
    public Result<?> updateMenuRole(Integer rid, Integer[] mids) throws SQLException {

        int delete = mapper.delete(new QueryWrapper<MenuRole>().eq("rid", rid));
        log.info("成功删除数据条目：{}",delete);

        if (mids == null || mids.length == 0) {
            return Result.success("更新成功");
        }
        Integer result = mapper.insertRecord(rid, mids);
        log.info("成功插入数据条目：{}",result);

        if (mids.length == result) {
            return Result.success("更新成功");
        }
        log.error("更新数据库失败：{}",this.getClass());
        throw new SQLException("更新角色菜单时发生异常，数据库回滚！传入的参数：rid："+rid+"，mids的长度："+mids.length);



    }
}
